package com.example.websocket.config.core;

import java.util.concurrent.ConcurrentHashMap;

public class ThreadLocalCacheUser {

    private ThreadLocalCacheUser() {
    }


    private static final ThreadLocal<ConcurrentHashMap<Integer, String>> CACHE_USER = new ThreadLocal<>();

    /**
     * 清除用户信息
     */
    public static void clear() {
        CACHE_USER.remove();
    }

    /**
     * 存储用户信息
     */
    public static void set(Integer id, String userName) {
        ConcurrentHashMap<Integer, String> concurrentHashMap = CACHE_USER.get();
        if (concurrentHashMap == null) {
            concurrentHashMap = new ConcurrentHashMap<>();
        }
        concurrentHashMap.put(id, userName);
        CACHE_USER.set(concurrentHashMap);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public static ConcurrentHashMap<Integer, String> get() {
        return CACHE_USER.get();
    }

}
